from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from tortoise.exceptions import DoesNotExist, IntegrityError, ValidationError, OperationalError
from config import settings
from core import Events, Router, Expception

application = FastAPI(
    debug=settings.APP_DEBUG,
    swagger_ui_css="static/swagger-ui.css",
    swagger_ui_js="static/swagger-ui-bundle.js",
)
# 路由调用
# 路由
application.include_router(Router.router)
# 时间监听
application.add_event_handler("startup", Events.start_up(application))
application.add_event_handler("shutdown", Events.shutdown(application))

# 异常错误处理
application.add_exception_handler(HTTPException, Expception.http_error_handler)
application.add_exception_handler(RequestValidationError, Expception.http422_error_handler)
application.add_exception_handler(Expception.UnicornException, Expception.unicorn_exception_handler)
application.add_exception_handler(DoesNotExist, Expception.mysql_does_not_exist)
application.add_exception_handler(IntegrityError, Expception.mysql_integrity_error)
application.add_exception_handler(ValidationError, Expception.mysql_validation_error)
application.add_exception_handler(OperationalError, Expception.mysql_operational_error)



# 添加中间件
# 添加跨域中间件
application.add_middleware(
    CORSMiddleware,
    allow_origins=settings.CORS_ORIGINS,
    allow_credentials=settings.CORS_ALLOW_CREDENTIALS,
    allow_methods=settings.CORS_ALLOW_METHODS,
    allow_headers=settings.CORS_ALLOW_HEADERS,
)

app = application
